<?php
/**
 * Created by PhpStorm.
 * User: Rain
 * Date: 2019/9/12
 * Time: 13:25
 */

namespace Rain\Admin\Services\Business\Controllers;


use Rain\Admin\Services\Models\AccessModel;
use Illuminate\Support\Facades\Gate;

class AccessService extends Base
{
    static protected $instance;

    protected $rely = [
        'AccessModel' => AccessModel::class,
    ];

    /**
     * 初始化权限
     */
    public function init(){
        // 权限列表
        $rules = $this -> AccessModel -> ruleList();

        foreach($rules as $rule){
            $permission = $rule -> value . '_' . strtoupper($rule -> method);

            Gate::define($permission, function ($user) use ($rule){
                return $this -> has($user, $rule -> value);
            });
        }
    }

    /**
     * 检查 当前用户是否拥有此权限
     *
     * @param $user
     * @param $rule
     * @return bool
     */
    public function has($user, $rule){
        $roles = $this -> AccessModel -> userRoles($user);

        foreach($roles  as $role){
            if ($role -> rules() -> pluck('value') -> contains($rule)) return true;
        }

        return false;
    }
}
